package com.websocket.wswbesocker.controller;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 监价websocket地Ht/myWs
 */
@ServerEndpoint("/myWs")
@Component
@Slf4j
public class WsServerEndpont {
    static Map<String, Session> sessionMap = new ConcurrentHashMap<>();//ConcurrentHashMap是线程安全的
    //连接建立时执行的操作
    @OnOpen
    public void onOpen(Session session) {
        // 当客户端连接时执行的操作
        sessionMap.put(session.getId(), session);//连接的时候加入
        log.info("webSocket is open");
    }
    //收到了客户端消息执行的操作
    @OnMessage
    public String onMessage(String message) {
        log.info("收到消息：" + message);
        return "已收到你的消息";
    }
    //连接关闭的时候执行的操作
    @OnClose
        public void onClose(Session session) {
        // 当客户端连接时执行的操作
        sessionMap.remove(session.getId());//关闭时候清除
        log.info("webSocket is close");
    }

    //每2s发送给客户端心跳消息
    @Scheduled(fixedRate = 2000)
    public void sendMag() throws IOException {
        for (String key : sessionMap.keySet()) {
            sessionMap.get(key).getBasicRemote().sendText("心跳");
        }
    }
}
